package com.eqdd.yiqidian.fragment.renshi;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.eqdd.yiqidian.BumenListFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CareerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.DepartmentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.TapActivity;
import com.eqdd.yiqidian.ui.gongneng.renshi.zuzhiguanli.CareerDescActivity;
import com.eqdd.yiqidian.ui.gongneng.renshi.zuzhiguanli.InvitePersonToComActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function3;

/**
 * Created by lvzhihao on 17-4-27.
 */

public class BumenListFragment extends BaseFragment {

    private BumenListFragmentCustom databinding;
    private EditDialogFragment editDiglog;
    private ActionSheetDialog bottomChooseCareer;
    private DepartmentListResultBean departmentListResultBean;
    private List<CareerListResultBean> careerList;
    private ArrayList<Object> datas;
    private SlimAdapterEx slimAdapterEx;
    private CareerListResultBean careerChoose;
    private DepartmentListResultBean departmentChoose;
    private ActionSheetDialog bottomChoose;
    private List<DepartmentListResultBean> departList;
    private List<EmploymentListResultBean> employList;

    @Override
    protected void setView() {
        if (slimAdapterEx == null) {
            databinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

            slimAdapterEx = SlimAdapterEx.create().register(R.layout.item_edit_title_type, new SlimInjector<String>() {
                @Override
                public void onInject(String data, IViewInjector injector) {
                    injector.text(R.id.tv_top_title, data);
                }
            }).register(R.layout.list_item_section, new SlimInjector<CareerListResultBean>() {
                @Override
                public void onInject(CareerListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_name, data.getName());
                }
            }).register(R.layout.list_item_section, new SlimInjector<DepartmentListResultBean>() {
                @Override
                public void onInject(DepartmentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_name, data.getDepartName());
                }
            }).register(R.layout.list_item_10, new SlimInjector<EmploymentListResultBean>() {
                @Override
                public void onInject(EmploymentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_upper_left_content, data.getStaffName())
                            .text(R.id.tv_upper_right_content, data.getDepartName())
                            .text(R.id.tv_down_right_content, data.getPostName())
                            .text(R.id.tv_down_left_content, data.getUname())
                            .with(R.id.iv_head, v -> {
                                ImageUtil.setCircleImage(data.getIphoto(), (ImageView) v);
                            })
                            .invisible(R.id.iv_enter);
                }
            })
                    .attachTo(databinding.recyclerView);
            ItemClickSupport.addTo(databinding.recyclerView).setOnItemClickListener((rv, p, v) -> {

                if (slimAdapterEx.getData().get(p) instanceof DepartmentListResultBean) {
                    departmentChoose = (DepartmentListResultBean) slimAdapterEx.getData().get(p);
                    ((TapActivity) getActivity()).addFragment(departmentChoose);
                } else if (slimAdapterEx.getData().get(p) instanceof CareerListResultBean) {
                    CareerListResultBean career = (CareerListResultBean) slimAdapterEx.getData().get(p);

                    Bundle bundle = new Bundle();
                    bundle.putInt(Config.ID,career.getId());
                    bundle.putString("postName",career.getName());
                    bundle.putString("depName",departmentListResultBean.getDepartName());
                    startActivity(CareerDescActivity.class,bundle);
                }

            })
                    .setOnItemLongClickListener((rv, p, v) -> {

                        if (slimAdapterEx.getData().get(p) instanceof CareerListResultBean) {
                            careerChoose = (CareerListResultBean) slimAdapterEx.getData().get(p);
                            bottomChooseCareer.show();
                        } else if (slimAdapterEx.getData().get(p) instanceof DepartmentListResultBean) {
                            departmentChoose = (DepartmentListResultBean) slimAdapterEx.getData().get(p);
                            bottomChoose.show();
                        }
                        return false;

                    });
            refresh();

        }
    }

    public void refresh() {
        ((BaseActivity) getActivity()).showLoading();
        Flowable<String> departFlow = OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.Select_SECTION)
                .params("ParentId", departmentListResultBean.getDepartId())
                .params("CompanyId", departmentListResultBean.getCompanyId())
                .converter(new StringConvert())
                .adapt(new FlowableBody<String>());
        Flowable<String> careerFlow = OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.SELECT_CAREER)
                .params("companyId", departmentListResultBean.getCompanyId())
                .params("departId", departmentListResultBean.getDepartId())
                .converter(new StringConvert())
                .adapt(new FlowableBody<String>());
        Flowable<String> employmentFlow = OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.SELECT_EMPLOYMENT)
                .params("departId", departmentListResultBean.getDepartId())
                .params("companyId", departmentListResultBean.getCompanyId())
                .converter(new StringConvert())
                .adapt(new FlowableBody<String>());
        Flowable.combineLatest(departFlow, careerFlow, employmentFlow, new Function3<String, String, String, Object>() {
            @Override
            public Object apply(@NonNull String s, @NonNull String s2, @NonNull String s3) throws Exception {

                HttpResult<List<DepartmentListResultBean>> httpResultDepartList = new Gson().fromJson(s, new TypeToken<HttpResult<List<DepartmentListResultBean>>>() {
                }.getType());
                if (httpResultDepartList.getStatus() == 200) {
                    departList = httpResultDepartList.getItems();
                }
                HttpResult<List<CareerListResultBean>> httpResultCareerList = new Gson().fromJson(s2, new TypeToken<HttpResult<List<CareerListResultBean>>>() {
                }.getType());
                if (httpResultCareerList.getStatus() == 200) {
                    careerList = httpResultCareerList.getItems();
                }
                HttpResult<List<EmploymentListResultBean>> httpResultEmployList = new Gson().fromJson(s3, new TypeToken<HttpResult<List<EmploymentListResultBean>>>() {
                }.getType());
                if (httpResultCareerList.getStatus() == 200) {
                    employList = httpResultEmployList.getItems();
                }
                return "1";
            }
        })
                .subscribe((s) -> {
                    datas.clear();
                    if (!ListUtil.isEmpty(departList)) {
                        datas.add("部门");
                        datas.addAll(departList);
                    }
                    if (!ListUtil.isEmpty(careerList)) {
                        datas.add("职位");
                        datas.addAll(careerList);
                    }
                    if (!ListUtil.isEmpty(employList)) {
                        datas.add("人员");
                        datas.addAll(employList);
                    }
                    slimAdapterEx.updateData(datas);
                }, e -> {
                    ToastUtil.showShort(Config.SERVER_ERROR);
                    System.out.println(e.toString());
                    ((BaseActivity) getActivity()).hideLoading();
                }, () -> {
                    ((BaseActivity) getActivity()).hideLoading();
                });

    }

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        departmentListResultBean = arguments.getParcelable(Config.DEPARTMENT);
        initChooseDialog();
        initChooseDialogCareer();
        datas = new ArrayList<>();
    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return databinding = DataBindingUtil.inflate(inflater, R.layout.fragment_bumen_list, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initChooseDialog() {
        bottomChoose = ChooseAlertView.getBottomChoose(getActivity(), null, new String[]{"删除部门", "修改部门名称"}, (v, p) -> {
            switch (p) {
                case 1:
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.DELETE_SECTION)
                            .params("companyId", departmentChoose.getCompanyId())
                            .params("departId", departmentChoose.getDepartId())
                            .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        refresh();
                                    }
                                }
                            });
                    break;
                case 2:
                    editDiglog = ChooseAlertView.getEditDiglog("部门名称", null, null, (content) -> {
                        if (TextUtils.isEmpty(content.get(0))) {
                            ToastUtil.showLong("信息不完整，修改失败");
                            return;
                        }
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_SECTION)
                                .params("name", content.get(0))
                                .params("describe", departmentChoose.getDeac())
                                .params("userGuid", GreenDaoUtil.getUser().getGuid())
                                .params("id", departmentChoose.getDepartId())
                                .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {
                                            refresh();
                                        }
                                    }
                                });
                    });
                    editDiglog.show(getChildFragmentManager(), "edit");
                    break;
            }
        });
    }

    private void initChooseDialogCareer() {
        bottomChooseCareer = ChooseAlertView.getBottomChoose(getActivity(), null, new String[]{"删除职位", "修改职位名称", "邀请入职"}, (v, p) -> {
            switch (p) {
                case 1:
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.DELETE_CAREER)
                            .params("postId", careerChoose.getId())
                            .params("companyId", careerChoose.getCompanyid())
                            .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        refresh();
                                    }
                                }
                            });
                    break;
                case 2:
                    editDiglog = ChooseAlertView.getEditDiglog("职位名称", null, null, (content) -> {
                        if (TextUtils.isEmpty(content.get(0))) {
                            ToastUtil.showLong("信息不完整，修改失败");
                            return;
                        }
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.UPDATE_CAREER)
                                .params("name", content.get(0))
                                .params("type", careerChoose.getType())
                                .params("desc", careerChoose.getDesc())
                                .params("userGuid", GreenDaoUtil.getUser().getGuid())
                                .params("id", careerChoose.getId() + "")
                                .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {
                                            refresh();
                                        }
                                    }
                                });
                    });
                    editDiglog.show(getChildFragmentManager(), "edit");
                    break;
                case 3:
                    Bundle bundle = new Bundle();
                    bundle.putString(Config.DEPARTMENT_NAME, departmentListResultBean.getDepartName());
                    bundle.putString(Config.DEPARTMENT_ID, careerChoose.getDepartid() + "");
                    bundle.putString(Config.CAREER_ID, careerChoose.getId() + "");
                    bundle.putString(Config.CAREER_NAME, careerChoose.getName());
                    startActivity(InvitePersonToComActivity.class, bundle);
                    break;
            }
        });
    }
}
